﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Cfg;
using NHibernate;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using Mapping;
using System.Runtime.Remoting.Messaging;

namespace FactoryOfSessions
{
    public class SessionsFactory
    {
        private static ISessionFactory sessionFactory;
        public static Configuration Config { get; private set; }
        
        private static ISession threadSession //Сама сессия
        {
            get
            {
                return (ISession)CallContext.GetData("THREAD_SESSION"); //Сессию мы храним в контексте, вот так работать с контекстом
            }
            set
            {
                CallContext.SetData("THREAD_SESSION", value);
            }
        }

        public static void Init(String ServerName, String DBName)
        {
            Configure(ServerName, DBName);
            sessionFactory = Config.BuildSessionFactory();
        }

        private static void Configure(String ServerName, String DBName)
        {
            Config = Fluently.Configure().
                Database(
                    MsSqlConfiguration
                        .MsSql2008
                        .ConnectionString(x => x
                            .Server(ServerName)
                            .Database(DBName)
                            .TrustedConnection())
                            .UseReflectionOptimizer())
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<DisciplineMap>())
                .BuildConfiguration();
        }
        
        public static ISession GetSession() 
        {
            ISession session = threadSession; 
            if (session == null)
            {
                session = sessionFactory.OpenSession();
                threadSession = session;
            }
            return session;
        }
    }
}
